import { createStore } from "vuex";
import vuexPersist from "vuex-persist";
export default createStore({
  state: {
    shopcar: [],
    //购物车数据
    checked: false,
    //全选按钮
  },
  mutations: {
    add(state, obj) {
      let flag = false;
      state.shopcar.forEach((item) => {
        if (item.id == obj.id) {
          flag = true;
          item.num += obj.num;
        }
      });

      if (flag == false) {
        obj.status = false;
        //新添加一个字段 状态是未选中的
        state.shopcar.push(obj);
      }
    },
    changeItem(state) {
      state.checked = state.shopcar.every((item) => {
        return item.status == true;
      });
    },
    //点击上面的复选框控制 全选按钮

    checkAll(state) {
      state.shopcar.forEach((item) => {
        item.status = state.checked;
      });
    },
    //全选

    del(state) {
      state.shopcar = state.shopcar.filter((item) => {
        return item.status == false;
      });
      state.checked = false;
    },
    //选中删除
  },
  actions: {},
  modules: {},
  getters: {
    allNum(state) {
      let allnum = 0;
      state.shopcar.forEach((item) => {
        allnum += item.num;
      });
      return allnum;
    },
    //计算购物车里所有的商品的数量
  },

  plugins: [
    new vuexPersist({
      storage: window.localStorage,
    }).plugin,
  ],
});
